package com.jdew.thkj.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.PddDetailBean;
import com.jdew.thkj.bean.PddlinkBean;
import com.jdew.thkj.dialog.CommonDialog;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.manager.BannerViewHolder;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangzai on 2018/8/10.
 */

public class PddDetailActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.name)
    TextView name;
    @Bind(R.id.ymoney)
    TextView ymoney;
    @Bind(R.id.upgrade)
    TextView upgrade;
    @Bind(R.id.quanhou)
    TextView quanhou;
    @Bind(R.id.salenum)
    TextView salenum;
    @Bind(R.id.share)
    TextView share;
    @Bind(R.id.copy)
    TextView copy;
    @Bind(R.id.money)
    TextView money;
    @Bind(R.id.lianjie)
    TextView lianjie;
    @Bind(R.id.ptitle)
    TextView ptitle;
    @Bind(R.id.banner)
    MZBannerView banner;
    @Bind(R.id.paste)
    TextView paste;
    @Bind(R.id.save)
    TextView save;
    @Bind(R.id.quan)
    TextView quan;
    @Bind(R.id.beforeprice)
    TextView yuanPrice;
    @Bind(R.id.nowprice)
    TextView nowprice;
    @Bind(R.id.shoucang)
    ImageView shoucang;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.zhuan)
    TextView tv_zhuan;
    @Bind(R.id.name2)
    TextView name2;
    @Bind(R.id.source)
    ImageView source;
    @Bind(R.id.collection_view)
    LinearLayout collection;
    @Bind(R.id.share_view)
    LinearLayout shareView;
    @Bind(R.id.quan_view)
    LinearLayout quanView;
    @Bind(R.id.shop)
    ImageView shop;
    @Bind(R.id.shopname)
    TextView shopname;
    @Bind(R.id.shorturl)
    TextView shorturl;
    private String maType;
    private SharedPreferences sp;
    private String shareUrl;
    private SharedPreferences.Editor editor;
    private String itemId;
    private List<String> list = new ArrayList<>();
    private DecimalFormat df = new DecimalFormat("0.00");
    private String openUrl;
    private String collectionState;
    private String url;
    private String des;
    private String before;
    private String youhuiquan;
    private String volume;
    private String presentprice;

    @Override
    public int bindLayout() {
        return R.layout.activity_pdd_product_detail;
    }

    @Override
    public void initView(View view) {
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        title.setText("商品详情");
        yuanPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        maType = sp.getString("SpareTwo", "");
        itemId = getIntent().getStringExtra("itemId");
        getState();
        GetSingleproduct();
        GetPromotion();
        copy.setOnClickListener(this);
        quan.setOnClickListener(this);
        paste.setOnClickListener(this);
        share.setOnClickListener(this);
        collection.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.copy: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                    return;
                }
                openPdd();
            }
            break;
            case R.id.quan: {
                if (maType.equals("") || maType.equals("1")) {
                    dosure();
                    return;
                }
                openPdd();
            }
            break;
            case R.id.paste: {
                RegexValidateUtils.copyText(this, ptitle.getText().toString().replace("【", "").replace("】", "") + "\n" + "------------" + "\n" + money.getText().toString() + "\n" + "------------" + "\n" + nowprice.getText().toString() + "\n" + "------------" + "\n" + save.getText().toString() + "\n" + shareUrl);
                ToastUtils.getInstance(this).showMessage("复制成功");
            }
            break;
            case R.id.share: {
                Intent in = new Intent(PddDetailActivity.this, PddSharePictureActivity.class);
                in.putExtra("shareUrl", shareUrl);
                in.putExtra("itemid", itemId);
                startActivity(in);
            }
            break;
            case R.id.collection_view: {
                if (null != collectionState && collectionState.equals("1")) {
                    CanceltheCollection();
                } else {
                    getCollection();
                }
            }
            break;
            default:
                break;
        }
    }

    public void getCollection() {
        String userPhone = sp.getString("userPhone", "");
        if (null == url || null == des || null == before || null == presentprice || null == youhuiquan || null == volume) {
            ToastUtils.getInstance(this).showMessage("数据正在加载中，请稍后重试。");
            return;
        }
        HashMap<String, Object> map = new HashMap();
        map.put("UserId", userPhone);
        map.put("Goodsid", itemId);
        map.put("ImgUrl", url);
        map.put("Title", des);
        map.put("OriginalPrice", before);
        map.put("PresentPrice", presentprice);
        map.put("Coupon", youhuiquan);
        map.put("Volume", volume);
        map.put("Commission", tv_zhuan.getText().toString());
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).PDDCollection(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserId" + userPhone + "Goodsid" + itemId + "ImgUrl" + url + "Title" + des + "OriginalPrice" + before + "PresentPrice" + presentprice + "Coupon" + youhuiquan + "Volume" + volume + "Commission" + tv_zhuan.getText().toString())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("1")) {
                    collectionState = "1";
                    ToastUtils.getInstance(PddDetailActivity.this).showMessage("收藏成功");
                    shoucang.setImageResource(R.mipmap.sc);
                } else {
                    collectionState = "-1";
                    ToastUtils.getInstance(PddDetailActivity.this).showMessage("收藏失败");
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }

    public void CanceltheCollection() {
        String userPhone = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).PDDCanceltheCollection(userPhone, itemId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + userPhone + "Goodsid" + itemId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                    ToastUtils.getInstance(PddDetailActivity.this).showMessage("取消收藏成功");
                } else {
                    collectionState = "1";
                    shoucang.setImageResource(R.mipmap.sc);
                    ToastUtils.getInstance(PddDetailActivity.this).showMessage("取消收藏失败");
                }
            }
        });
    }

    public void GetSingleproduct() {
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetSingleproduct(itemId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "goodsid" + itemId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<PddDetailBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(PddDetailBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    quan.setText(bean.getData().get(0).getCoupon_discount() + "元优惠券");
                    if (bean.getData().get(0).getGoods_name().length() >= 22) {
                        name.setText(bean.getData().get(0).getGoods_name().substring(0, 22));
                        name2.setText(bean.getData().get(0).getGoods_name().substring(22, bean.getData().get(0).getGoods_name().length()));
                    } else {
                        name.setText(bean.getData().get(0).getGoods_name());
                    }
                    salenum.setText("销量:" + bean.getData().get(0).getSold_quantity());
                    money.setText("原价:" + df.format(Double.parseDouble(bean.getData().get(0).getMin_group_price())));
                    quanhou.setText("¥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_remain_quantity())));
                    SpannableString spannableString = new SpannableString(quanhou.getText().toString());
                    RelativeSizeSpan sizeSpan = new RelativeSizeSpan(1.2f);
                    spannableString.setSpan(sizeSpan, 0, quanhou.getText().toString().indexOf("."), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                    quanhou.setText(spannableString);
                    ptitle.setText(bean.getData().get(0).getGoods_name());
                    copy.setText("领券¥" + bean.getData().get(0).getCoupon_discount());
                    shop.setImageResource(R.mipmap.pdd_shop);
                    shopname.setText(bean.getData().get(0).getMall_name());
                    list.addAll(bean.getData().get(0).getGoods_gallery_urls());
                    banner.setPages(list, new MZHolderCreator<BannerViewHolder>() {
                        @Override
                        public BannerViewHolder createViewHolder() {
                            return new BannerViewHolder();
                        }
                    });
                    banner.setDelayedTime(5000);
                    banner.start();
                    //banner设置方法全部调用完毕时最后调用
                    banner.start();
                    source.setImageResource(R.mipmap.pdd_source);
                    nowprice.setText("现价:" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_remain_quantity())) + "元");
                    save.setText("节省:" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_discount())) + "元");
                    money.setText("原价:" + df.format(Double.parseDouble(bean.getData().get(0).getMin_group_price())) + "元");
                    yuanPrice.setText("原价:" + df.format(Double.parseDouble(bean.getData().get(0).getMin_group_price())));
                    lianjie.setText(bean.getData().get(0).getGoods_desc());
                    url = list.get(0);
                    des = bean.getData().get(0).getGoods_name();
                    before = df.format(Double.parseDouble(bean.getData().get(0).getMin_normal_price()));
                    presentprice = df.format(Double.parseDouble(bean.getData().get(0).getCoupon_remain_quantity()));
                    volume = bean.getData().get(0).getSold_quantity();
                    youhuiquan = bean.getData().get(0).getCoupon_discount();
                    if (maType.equals("1")) {
                        ymoney.setVisibility(View.GONE);
                        tv_zhuan.setVisibility(View.GONE);
                        shareView.setVisibility(View.GONE);
                        upgrade.setText("升级超级教练可享佣金￥" + Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount()));
                        if (Integer.parseInt(youhuiquan) > 0) {
                            copy.setText("自买省\n" + "￥" + youhuiquan);
                        } else {
                            copy.setText("领券");
                        }
                    } else if (maType.equals("2")) {
                        ymoney.setText("佣金:" + Double.parseDouble(bean.getData().get(0).getPromotion_rate()) / 2 + "%");
                        tv_zhuan.setText("赚 ￥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount()) / 2));
                        share.setText("分享赚\n¥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount()) / 2));
                        upgrade.setText("升级超级教练可享佣金￥" + bean.getData().get(0).getCoupon_min_order_amount());
                        if (Integer.parseInt(youhuiquan) > 0) {
                            copy.setText("自买省\n" + "￥" + youhuiquan + "+￥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount()) / 2));
                        } else {
                            copy.setText("自买省\n" + "￥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount()) / 2));
                        }
                    } else {
                        tv_zhuan.setText("赚 ￥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount())));
                        share.setText("分享赚\n¥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount())));
                        ymoney.setText("佣金:" + df.format(Double.parseDouble(bean.getData().get(0).getPromotion_rate())) + "%");
                        upgrade.setVisibility(View.GONE);
                        if (Integer.parseInt(youhuiquan) > 0) {
                            copy.setText("自买省\n" + "￥" + youhuiquan + "+￥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount())));
                        } else {
                            copy.setText("自买省\n" + "￥" + df.format(Double.parseDouble(bean.getData().get(0).getCoupon_min_order_amount())));
                        }
                    }
                } else if (bean.getCode().equals("-1")) {
                    ToastUtils.getInstance(PddDetailActivity.this).showMessage(bean.getMessage());
                    finish();
                }
            }
        });
    }

    public void GetPromotion() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).GetPromotion(itemId, sp.getString("userPhone", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", "") + "Goodsid" + itemId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<PddlinkBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(PddlinkBean bean) {
                if (bean.getCode().equals("0")) {
                    openUrl = bean.getData().get(0).getMobile_url();
                    shareUrl = bean.getData().get(0).getWe_app_web_view_short_url();
                    if (null != shareUrl) {
                        shorturl.setText(shareUrl);
                    }
                }
            }
        });
    }

    public void getState() {
        String userPhone = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).PDDGetState(userPhone, itemId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + userPhone + "Goodsid" + itemId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    shoucang.setImageResource(R.mipmap.sc);
                    collectionState = "1";
                } else {
                    collectionState = "-1";
                    shoucang.setImageResource(R.mipmap.sc_);
                }
            }
        });
    }

    public void dosure() {
        new CommonDialog.Builder(this)
                .setTitle("提示")
                .setMessage("此操作不可撤销，请确认余额" + youhuiquan + "元兑换此产品")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Duihuan();
                    }
                })
                .setNegativeButton("取消", null).show();
    }


    public void Duihuan() {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).SetBuy(sp.getString("userPhone", ""), youhuiquan, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + sp.getString("userPhone", "") + "Money" + youhuiquan)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject obj) {
                if (obj.getString("code").equals("0")) {
                    openPdd();
                }
                ToastUtils.getInstance(PddDetailActivity.this).showMessage(obj.getString("message"));
            }
        });
    }

    public void openPdd() {
        if (!RegexValidateUtils.checkHasInstalledApp(this, "com.xunmeng.pinduoduo")) {
            ToastUtils.getInstance(PddDetailActivity.this).showMessage("请先安装拼多多");
            return;
        }
        String content = "pinduoduo://com.xunmeng.pinduoduo/" + openUrl;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(content));
        startActivity(intent);
    }
}
